// pages/search/search.js
import request from '../../utils/request'
import { debounce } from '../../utils/utils'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    placeholderContent: '', //placeholder的内容
    hotList: [], // 热搜榜的数据
    searchContent: '', //用户输入的表单项数据
    searchList: [], // 关键字模糊匹配的数据
    historyList: [], // 搜索历史记录
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getInitData()
    this.getSearchHistory()
  },
  // 获取历史记录的功能函数
  getSearchHistory() {
    let historyList = wx.getStorageSync('historyList')
    if (historyList) {
      this.setData({
        historyList,
      })
    }
  },
  // 获取初始化的数据
  async getInitData() {
    let {
      data: { realkeyword },
    } = await request('/search/default')
    let { data: hotList } = await request('/search/hot/detail')
    this.setData({
      placeholderContent: realkeyword,
      hotList,
    })
  },
  //监听用户搜索的回调
  handleInputChange: debounce('inputControl', 400),
  // input函数防抖
  async inputControl(e) {
    let searchContent = e.detail.value.trim()
    this.setData({
      searchContent,
    })
    if (!searchContent)
      return this.setData({
        searchList: [],
      })
    // 发请求获取关键字模糊匹配数据
    let {
      result: { songs },
    } = await request('/search', {
      keywords: searchContent,
      limit: 10,
    })
    this.setData({
      searchList: songs,
    })
    // 将搜索的关键字添加到搜索历史记录中
    let { historyList } = this.data
    historyList.unshift(searchContent)
    historyList = [...new Set(historyList)]
    this.setData({
      historyList,
    })
    wx.setStorageSync('historyList', historyList)
  },
  // 点击清空搜索框内容触发的回调
  clearSearchContent() {
    this.setData({
      searchContent: '',
      searchList: [],
    })
  },
  // 删除搜索记录对应的回调
  deleteSearchHistory() {
    wx.showModal({
      content: '确认清空历史记录吗?',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#d43c33',
      success: result => {
        if (result.confirm) {
          this.setData({
            historyList: [],
          })
          wx.removeStorageSync('historyList')
        }
      },
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
})
